import 'dart:convert';

import 'package:flutter/services.dart' show rootBundle;
import 'package:vg_base/vg_string_util_lib.dart';

import 'vo/area_data.dart';
import 'vo/location_data.dart';

typedef CompleteCallback = void Function(bool initSuccess);

///省市区区域代码及名称
class LocationRepository{

  static LocationRepository _instance;

  LocationData _allLocationData;
  Map<String,LocalProvinceBean> _allProvinceMap;

  List<LocalProvinceBean> allProvinceList() => _allLocationData?.list;
  Map<String,LocalProvinceBean> allProvinceMap() => _allProvinceMap;

  LocationData allLocationData() => _allLocationData;

  LocationRepository._();
  static LocationRepository getInstance() {
    if (_instance == null) {
      _instance = new LocationRepository._();
    }
    return _instance;
  }

  init({CompleteCallback callback}) async{
    if(_allLocationData == null || _allLocationData?.list == null || _allLocationData.list.isEmpty){
      String locationJson = await rootBundle.loadString('assets/location.txt');
      if(StringUtils.isEmpty(locationJson)){
        if (callback != null) {
          callback(false);
        }
        return;
      }
      _allLocationData = LocationData.fromMap(json.decode(locationJson));
      _proccessToAllProvinceMap();
      if (callback != null) {
        callback(true);
      }
    }else{
      if (callback != null) {
        callback(true);
      }
    }
  }


  _proccessToAllProvinceMap(){

    if(_allLocationData == null || _allLocationData?.list == null || _allLocationData.list.isEmpty){
      return;
    }
    _allProvinceMap = Map();
    _allLocationData?.list?.forEach((element){
      if(element == null||StringUtils.isEmpty(element?.sid)){
        return;
      }
      _allProvinceMap["${element?.sid ?? ""}"] = element;
    });
  }

  dispose(){
    _allProvinceMap?.clear();
    _allLocationData = null;
    _instance = null;
  }
}